import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

import 'pic_preview_logic.dart';

class PicPreviewPage extends StatelessWidget {
  const PicPreviewPage({super.key});

  @override
  Widget build(BuildContext context) {
    final state = Get.find<PicPreviewLogic>().state;
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(children: [
        PhotoViewGallery.builder(
          scrollPhysics: const BouncingScrollPhysics(),
          builder: (BuildContext context, int index) {
            return PhotoViewGalleryPageOptions(
              imageProvider: _getImage(state.picList[index]),
              // initialScale: PhotoViewComputedScale.contained * 0.8,
              heroAttributes:
                  PhotoViewHeroAttributes(tag: state.picList[index]),
              onTapUp: (context, detail, value) {
                Get.back();
              },
            );
          },
          itemCount: state.picList.length,
          loadingBuilder: (context, event) => Center(
            child: SizedBox(
              width: 20.0,
              height: 20.0,
              child: CircularProgressIndicator(
                value: event == null
                    ? 0
                    : event.cumulativeBytesLoaded /
                        (event.expectedTotalBytes ?? 1),
              ),
            ),
          ),
          backgroundDecoration:
              BoxDecoration(color: Colors.grey.withAlpha(200)),
          pageController: PageController(initialPage: state.currentIndex.value),
          enableRotation: true,
          onPageChanged: (i) {
            state.currentIndex.value = i;
          },
        ),
        Positioned(
          left: 5,
          bottom: 5,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Obx(() {
              return Text(
                  "${state.currentIndex.value + 1}/${state.picList.length}");
            }),
          ),
        )
      ]),
    );
  }

  _getImage(String url) {
    if (url.startsWith("http")) {
      return NetworkImage(url);
    } else {
      return FileImage(File(url));
    }
  }
}
